import axios from "axios";
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
} from "axios";
import { error } from "@/utils/toast";
import { 
  getAccessToken, 
  getRefreshToken, 
  setAccessToken, 
  setRefreshToken, 
  setAccessTokenExpires, 
  setRefreshTokenExpires,
  clearAuth,
  isRefreshTokenExpired 
} from "./auth";
import router from "@/router";
import type { ApiResponse } from "@/types";
import { confirm } from "@/utils/confirm";
import { refreshToken } from "@/api/auth";
import { API_CONFIG } from "@/config";

// 防止重复刷新token的标志
let isRefreshing = false;
let failedQueue: Array<{
  resolve: (value?: any) => void;
  reject: (reason?: any) => void;
}> = [];

// 处理队列中的请求
const processQueue = (error: any, token: string | null = null) => {
  failedQueue.forEach(({ resolve, reject }) => {
    if (error) {
      reject(error);
    } else {
      resolve(token);
    }
  });
  
  failedQueue = [];
};

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.DEV
    ? "/api" // 开发环境使用代理路径
    : import.meta.env.VITE_API_BASE_URL || "/api",
  timeout: API_CONFIG.REQUEST_CONFIG.TIMEOUT, // 增加超时时间以适应网络环境
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证头
    const token = getAccessToken();
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error("Request error:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: any) => {
    const { data } = response;
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    if (response.status === 200) {
      // 检查是否是导出接口（返回纯文本数据）
      if (response.config.url?.includes('/export') || response.config.url?.includes('exportInfos')) {
        // 导出接口直接返回原始数据
        return Promise.resolve({ data: data });
      }
      
      // 根据业务状态码判断请求是否成功
      if (data.code === 200 || data.success) {
        return Promise.resolve(data);
      } else {
        // 业务错误
        error(data.msg || "请求失败");
        return Promise.reject(new Error(data.msg || "请求失败"));
      }
    } else {
      error("网络错误");
      return Promise.reject(new Error("网络错误"));
    }
  },
  async (e) => {
    console.error("Response error:", e);

    const originalRequest = e.config;

    if (e.response) {
      const { status, data } = e.response;

      switch (status) {
        case 401:
          // 如果是刷新token的请求失败，直接跳转登录页
          if (originalRequest.url?.includes('/auth/refresh')) {
            clearAuth();
            router.push("/login");
            return Promise.reject(e);
          }

          // 如果正在刷新token，将请求加入队列
          if (isRefreshing) {
            return new Promise((resolve, reject) => {
              failedQueue.push({ resolve, reject });
            }).then(token => {
              originalRequest.headers.Authorization = `Bearer ${token}`;
              return service(originalRequest);
            }).catch(err => {
              return Promise.reject(err);
            });
          }

          // 检查refreshToken是否过期
          if (isRefreshTokenExpired()) {
            confirm.custom({
              message: "登录已过期，请重新登录",
              title: "提示",
              confirmButtonText: "确定",
              type: "warning",
              showCancelButton: false
            }).then(() => {
              clearAuth();
              router.push("/login");
            }).catch(() => {
              clearAuth();
              router.push("/login");
            });
            return Promise.reject(e);
          }

          // 尝试刷新token
          isRefreshing = true;
          const refreshTokenValue = getRefreshToken();
          
          if (!refreshTokenValue) {
            clearAuth();
            router.push("/login");
            return Promise.reject(e);
          }

          try {
            const accessTokenValue = getAccessToken();
            const response = await refreshToken(accessTokenValue || '', refreshTokenValue);
            const { data: tokenData } = response;
            
            // 更新token信息
            setAccessToken(tokenData.accessToken);
            setRefreshToken(tokenData.refreshToken);
            setAccessTokenExpires(tokenData.accessTokenExpires);
            // 更新请求头
            originalRequest.headers.Authorization = `Bearer ${tokenData.accessToken}`;
            
            // 处理队列中的请求
            processQueue(null, tokenData.accessToken);
            
            // 重新发送原始请求
            return service(originalRequest);
          } catch (refreshError) {
            // 刷新失败，清除认证信息并跳转登录页
            processQueue(refreshError, null);
            clearAuth();
            router.push("/login");
            return Promise.reject(refreshError);
          } finally {
            isRefreshing = false;
          }
          break;
        case 403:
          error("没有权限访问该资源");
          break;
        case 404:
          error("请求的资源不存在");
          break;
        case 500:
          error("服务器内部错误");
          break;
        default:
          error(data?.message || `请求错误 ${status}`);
      }
    } else if (e.code === "ECONNABORTED") {
      error("请求超时，请稍后重试");
    } else {
      error("网络连接异常，请检查网络");
    }

    return Promise.reject(e);
  }
);

// 封装常用的HTTP方法
export default {
  /**
   * GET 请求
   */
  get<T = any>(url: string, params?: any): Promise<ApiResponse<T>> {
    return service.get(url, { params });
  },

  /**
   * POST 请求
   */
  post<T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> {
    return service.post(url, data, config);
  },

  /**
   * PUT 请求
   */
  put<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return service.put(url, data);
  },

  /**
   * DELETE 请求
   */
  delete<T = any>(url: string, params?: any): Promise<ApiResponse<T>> {
    return service.delete(url, { params });
  },
  deleteData<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return service.delete(url,  data );
  },

  /**
   * 上传文件
   */
  upload<T = any>(url: string, formData: FormData): Promise<ApiResponse<T>> {
    return service.post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 下载文件
   */
  download(url: string, params?: any): Promise<Blob> {
    return service.get(url, {
      params,
      responseType: "blob",
    });
  },

  /**
   * 并发请求
   */
  all<T = any>(requests: Promise<any>[]): Promise<T[]> {
    return Promise.all(requests);
  },

  /**
   * 取消请求
   */
  cancelToken() {
    return axios.CancelToken.source();
  },

  /**
   * 判断是否取消请求
   */
  isCancel(error: any): boolean {
    return axios.isCancel(error);
  },
};

// 导出 axios 实例，供其他地方使用
export { service };
